﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Interface.Admin;
using NetDon.OA.Interface.Configuration;
using NetDon.OA.Portal.Constants;
using NineRays.WebControls;
using ServiceContainer = NetDon.Utilities.ServiceContainer;
using NetDon.Utilities;
namespace NetDon.OA.Portal.Admin
{
    [Command(ButtonConstants.CommandNames.CreatePosition, ButtonConstants.CommandImages.CreateRoot, Order = 0, CausesValidation = false)]

    [Command(ButtonConstants.CommandNames.Save, ButtonConstants.CommandImages.Save, Order = 1, CausesValidation = true)]
    [Command(ButtonConstants.CommandNames.Delete, ButtonConstants.CommandImages.Delete, Order = 2, CausesValidation = false)]
    [Navigation("组织架构管理", "岗位管理")]
    [PageTabber(Index = 0, NavigateUrl = "~/Admin/CompanyConfig.aspx", Title = "组织架构管理", Type = typeof(CompanyConfig))]
    [PageTabber(Index = 1, NavigateUrl = "~/Admin/PositionConfig.aspx", Title = "岗位管理", Type = typeof(PositionConfig))]
    public partial class PositionConfig : PageBase
    {
        public Guid Id
        {
            get { return ViewState["Id"] != null ? (Guid)ViewState["Id"] : Guid.Empty; }

            set { ViewState["Id"] = value; }
        }

        public Guid? ParentID
        {
            get { return ViewState["ParentID"] != null ? (Guid?)ViewState["ParentID"] : null; }

            set
            {
                ViewState["ParentID"] = value == Guid.Empty ? null : value;
            }
        }

        public PositionNodeType CurrentNodeType
        {
            get { return ViewState["CurrentNodeType"] != null ? (PositionNodeType)ViewState["CurrentNodeType"] : PositionNodeType.Position; }

            set { ViewState["CurrentNodeType"] = value; }
        }
        public PositionNodeType NewNodeType
        {
            get { return ViewState["NewNodeType"] != null ? (PositionNodeType)ViewState["NewNodeType"] : PositionNodeType.Root; }

            set { ViewState["NewNodeType"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ControlHelper.SetFreeTextBoxEditor(txtDescription);
                this.pnlCompanyInfo.Visible = false;
                BindControls();
                ShowButtons();
            }
        }

        private void ShowButtons()
        {
            if (Id == Guid.Empty)
            {
                CommandButtons[ButtonConstants.CommandNames.Delete].Visible = false;
                CommandButtons[ButtonConstants.CommandNames.CreatePosition].Visible = true;
                CommandButtons[ButtonConstants.CommandNames.Save].Visible = true;
                if (CurrentNodeType == PositionNodeType.Root && ParentID == null && NewNodeType == PositionNodeType.Root)
                {


                    CommandButtons[ButtonConstants.CommandNames.Save].Visible = false;

                }

            }
            else
            {
                CommandButtons[ButtonConstants.CommandNames.Delete].Visible = true;

                CommandButtons[ButtonConstants.CommandNames.CreatePosition].Visible = true;
                CommandButtons[ButtonConstants.CommandNames.Save].Visible = true;
            }


        }

        private void BindControls()
        {
            BindPostion();

        }

        private void BindPostion()
        {
            var service = ServiceContainer.GetService<IPostService>();
            var rootCategories = service.GetRootPosts();
            treeCompany.Nodes.Clear();
            //add root company
            treeCompany.Nodes.Add(CreateRootNode());
            for (int i = 0; i < rootCategories.Count; i++)
            {
                treeCompany.Nodes[0].ChildNodes.Add(CreatePositionTreeNode(rootCategories[i]));
            }

            treeCompany.Nodes[0].Text =
                Server.HtmlEncode(SystemConfiguration.RootPositionName);
            treeCompany.Nodes[0].PopulateNodesOnDemand = rootCategories.Count > 0 ? true : false;
            treeCompany.SelectedNode = treeCompany.Nodes[0];
            Id = Guid.Empty;
            ParentID = null;
            CurrentNodeType = PositionNodeType.Root;
            NewNodeType = PositionNodeType.Root;
        }

        private FlyTreeNode CreateRootNode()
        {
            return new FlyTreeNode(
                            Server.HtmlEncode(SystemConfiguration.RootPositionName),
                            Guid.Empty.ToString())
            {
                NodeTypeID = NodeType.Root.ToString(),
                ImageUrl = ApplicationImages.TreeNodeClosed,
                SelectedImageUrl = ApplicationImages.TreeNodeOpened,
                Expanded = true,
                ExpandLevel = 99,
                Tag = -1
            };
        }

        protected void treeCompany_PopulateNodes(object sender, FlyTreeNodeEventArgs e)
        {
            if (e.Node.ChildNodes.Count <= 0)
            {
                LoadChildNodes(e.Node);
            }
        }

        private FlyTreeNode CreatePositionTreeNode(PostData postData)
        {
            return new FlyTreeNode(
                            Server.HtmlEncode(postData.PostName),
                            postData.PostId.ToString())
            {
                NodeTypeID = PositionNodeType.Position.ToString(),
                PopulateNodesOnDemand = postData.HasChildren,
                ImageUrl = ApplicationImages.TreeNodeClosed,
                SelectedImageUrl = ApplicationImages.TreeNodeOpened,
                Tag = postData.NodeLevel
            };
        }

        private void LoadChildNodes(FlyTreeNode node)
        {
            if (node.ChildNodes.Count <= 0)
            {
                //load companies
                var service = ServiceContainer.GetService<IPostService>();
                var childCompanies = (PostDataCollection)service.GetPost(node.Value.ToGuid()).GetChildren();
                for (int i = 0; i < childCompanies.Count; i++)
                {
                    node.ChildNodes.Add(CreatePositionTreeNode(childCompanies[i]));

                }


            }
        }

        private void CreatePosition()
        {
            //parent Category is Root
            ClearControl();
            Id = Guid.Empty;
            ParentID = treeCompany.SelectedNode.Value.ToGuid();
            txtParentName.Text = treeCompany.SelectedNode.Text.Trim();
            pnlCompanyInfo.Visible = true;

            this.NewNodeType = PositionNodeType.Position;
            if (this.treeCompany.SelectedNode.Tag.ToString() == "-1")
                txtNodeLevel.Text = "1";
            else
            {
                txtNodeLevel.Text = (this.treeCompany.SelectedNode.Tag.ToString().ToInt32() + 1).ToString();
            }
        }



        protected void ClearControl()
        {
            //clear company
            txtParentName.Text = string.Empty;
            txtPostName.Text = string.Empty;
            ddlPostLevel.SelectedValue = string.Empty;
            txtDescription.Text = string.Empty;
            txtNodeLevel.Text = string.Empty;


        }

        protected void btnModify_Click(object sender, EventArgs e)
        {

            if (treeCompany.SelectedNode.NodeTypeID == PositionNodeType.Root.ToString())
            {
                Id = Guid.Empty;
                ParentID = null;
                CurrentNodeType = PositionNodeType.Root;
                NewNodeType = PositionNodeType.Root;
                pnlCompanyInfo.Visible = false;

            }
            else if (this.treeCompany.SelectedNode.NodeTypeID == PositionNodeType.Position.ToString())
            {
                pnlCompanyInfo.Visible = true;

            }

            ShowButtons();
            InitPositon();

        }

        private void InitPositon()
        {
            if (this.treeCompany.SelectedNode.NodeTypeID == PositionNodeType.Position.ToString())
            {
                var service = ServiceContainer.GetService<IPostService>();
                var post = service.GetPost(treeCompany.SelectedNode.Value.ToGuid());
                if (post != null)
                {
                    txtPostName.Text = post.PostName;

                    //add more 
                    if (!post.ParentId.HasValue)
                        txtParentName.Text = SystemConfiguration.RootPositionName;
                    else
                        txtParentName.Text = service.GetPost(post.ParentId.Value).PostName;

                    txtNodeLevel.Text = post.NodeLevel.Value.ToString();
                    ddlPostLevel.SelectedValue = post.PostLevel.ToString();
                    txtDescription.Text = post.Comments;

                    Id = treeCompany.SelectedNode.Value.ToGuid();
                    ParentID = post.ParentId;
                    CurrentNodeType = PositionNodeType.Position;
                    ShowButtons();
                }
            }


        }

        private void SaveCompany()
        {
            if (string.IsNullOrEmpty(this.ddlPostLevel.SelectedValue))
            {
                Alert("请选择岗位等级！");
                return;
            }
            var data = new PostData()
                           {
                               ParentId = ParentID,
                               PostName = this.txtPostName.Text.Trim(),

                               Comments = this.txtDescription.Text.Trim(),
                               PostId = Guid.NewGuid(),

                               PostLevel = this.ddlPostLevel.SelectedValue.ToGuid(),
                               NodeLevel = Convert.ToInt32(this.txtNodeLevel.Text)
                           };
            if (Id != Guid.Empty) data.PostId = Id;
            var service = ServiceContainer.GetService<IPostService>();
            bool result = Id == Guid.Empty ? service.AddPost(data) : service.ModifyPost(data);
            if (result)
            {
                if (Id == Guid.Empty)
                {
                    var node = CreatePositionTreeNode(data);
                    if (ParentID.HasValue)
                    {
                        var parentNode = treeCompany.FindByValue(ParentID.Value.ToString());
                        parentNode.ChildNodes.Add(node);
                    }
                    else
                    {
                        treeCompany.Nodes[0].ChildNodes.Add(node);
                    }
                    treeCompany.SelectedNode = node;
                    Id = data.PostId;
                }
                else
                {
                    treeCompany.FindByValue(Id.ToString()).Text = Server.HtmlEncode(data.PostName);
                }
                ShowButtons();
                base.Success("保存职位成功！");
            }
            else
            {
                ShowDataError(data);
            }
        }

        protected override void OnCommand(CommandEventArgs args)
        {
            var service = ServiceContainer.GetService<IPostService>();
            switch (args.CommandName)
            {
                case ButtonConstants.CommandNames.Delete:
                    {
                        var companyId = treeCompany.SelectedNode.Value.ToGuid();


                        if (service.CheckPostUsed(companyId))
                        {

                            Alert(
                                string.Format("职位{0}被使用，不能被删除。", treeCompany.SelectedNode.Text));
                            return;
                        }


                        string selectedNode = string.Empty;
                        if (service.RemovePost(companyId))
                        {
                            if (treeCompany.SelectedNode.Parent != null)
                            {

                                FlyTreeNode parentNode = treeCompany.SelectedNode.Parent;

                                treeCompany.SelectedNode.Parent.ChildNodes.Remove(
                              treeCompany.SelectedNode);
                                if (parentNode.ChildNodes.Count > 0)
                                    selectedNode = parentNode.ChildNodes[0].Value;
                                else
                                    selectedNode = parentNode.Value;
                            }
                            else
                            {

                                selectedNode = treeCompany.Nodes[0].ChildNodes[0].Value;
                                treeCompany.Nodes[0].ChildNodes.Remove(treeCompany.SelectedNode);
                            }

                            Id = Guid.Empty;
                            ClearControl();
                            if (selectedNode == string.Empty)
                                treeCompany.SelectedNode = treeCompany.Nodes[0];
                            else
                                treeCompany.SelectedNode = treeCompany.FindByValue(selectedNode);

                        }
                        btnModify_Click(null, null);
                    }
                    break;



                case ButtonConstants.CommandNames.CreatePosition:
                    CreatePosition();
                    ShowButtons();
                    break;
                case ButtonConstants.CommandNames.Save:

                    SaveCompany();

                    break;
            }
        }


    }


}
